package com.sc.sc250601.cook.interceptor;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.sc.sc250601.cook.pojo.Result;
import com.sc.sc250601.cook.util.JwtUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

//@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 设置请求和响应编码的方式
        request.setCharacterEncoding("utf-8");
        //response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        // 获取前端请求头传递的token信息
        String token = request.getHeader("token");
        System.out.println("token信息："+token);
        // 合法直接 return
        if(JwtUtils.checkToken(token)) {
            return true;
        }

        PrintWriter out = response.getWriter();
        // new ObjectMapper().writeValueAsString()
        // 把 java 对象转换成 json
        out.write(new ObjectMapper().writeValueAsString(new Result(0,"认证失败")));
        return false;
    }

}
